<template>
  <div>
    <div class="search">
      <input
        v-model="keyword"
        class="searchInput"
        type="text"
        placeholder="输入城市名或拼音"
        @input="input"
      />
    </div>
    <div class="searchCt" ref="searchCt" v-show="hasKeyword">
      <ul>
        <li
          v-for="item of searchList"
          :key="item.id"
          v-text="item.name"
          @click="chooseCity(item)"
        ></li>
        <li class="noCt" v-show="noList">暂无搜索内容</li>
      </ul>
    </div>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import BScroll from 'better-scroll'
export default {
  name: 'CitySearch',
  props: {
    cities: {
      required: true,
      type: Object
    }
  },
  data () {
    return {
      keyword: '',
      timer: null,
      searchList: []
    }
  },
  computed: {
    hasKeyword: function () {
      return this.keyword.trim() !== ''
    },
    noList: function () {
      return this.searchList.length === 0
    }
  },
  mounted: function () {
    this.scrollCt = new BScroll(this.$refs.searchCt)
  },
  methods: {
    ...mapActions({
      setCity: 'chooseCity'
    }),
    input: function () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(() => {
        const result = []
        const keyword = this.keyword.trim()
        for (let i in this.cities) {
          for (let val of this.cities[i]) {
            if (val.name.includes(keyword) || val.spell.includes(keyword)) {
              result.push(val)
            }
          }
        }
        this.searchList = result
      }, 100)
    },
    chooseCity: function (val) {
      this.currentCity = val.name
      this.setCity(val.name)
      this.$router.go(-1)
    }
  }
}
</script>

<style lang="stylus" scoped>
@import '~@styles/varibles.styl'
@import '~@styles/mixins.styl'
.search{
  height .72rem
  background $bgColor
  padding: 0 0.2rem 0.03rem;
  .searchInput{
    width 100%
    height .62rem
    padding 0 0.1rem
    line-height .62rem
    border-radius 0.06rem
    color $cityFtColor
    box-sizing border-box
  }
  .searchInput::-ms-input-placeholder{
    text-align center
  }
  .searchInput::-webkit-input-placeholder{
    text-align center
  }
  .searchInput:focus::-ms-input-placeholder{
    text-align left
  }
  .searchInput:focus::-webkit-input-placeholder{
    text-align left
  }
}
.searchCt{
  position fixed
  top 1.58rem
  bottom 0
  left 0
  right 0
  background #eee
  z-index 2
  overflow hidden
  ul{
    min-height 100%
    li{
      line-height .76rem
      padding-left .2rem
      background-color #ffffff
      color $cityFtColor
      border-bottom 1px solid $bdLineColor
    }
    .noCt{
       padding-left 0
       text-align center
    }
  }
}
</style>
